//
//  WBNetworkManager+Extension.swift
//  仿写微博
//
//  Created by Apple on 17/7/13.
//  Copyright © 2017年 tuimao. All rights reserved.
//

import UIKit
//MARK: 封装微博的网络请求
extension WBNetworkManager{
    //微博数据请求
    func statusList(since_id:Int64 = 0,max_id:Int64 = 0,completion:@escaping (_ list:[[String: AnyObject]]?,_ issuccess:Bool)->()){
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        let params = ["since_id":since_id,"max_id":max_id>0 ? (max_id-1) : 0]
        
        tokenRequest(URLString: urlString, parameters: params as [String : AnyObject]?) { (json, issuccess) in
            //从json中获取square_list字典数组
            let result = json?["statuses"] as? [[String: AnyObject]]
            completion(result, issuccess)
        }
    }
    
    /// 返回微博的未读数量 - 定时刷新，不需要提示是否失败！
    func unreadCount(completion: @escaping (_ count: Int)->()) {
        
        guard let uid = useAccount.uid else {
            return
        }
        
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        
        let params = ["uid": uid as AnyObject] as [String:AnyObject]
        
        tokenRequest(URLString: urlString, parameters: params) { (json, isSuccess) in
            let dict = json as? [String: AnyObject]
            
            let count = dict?["status"] as? Int
            
            completion(count ?? 0)
        }
    }
}
//用户信息的网络请求
extension WBNetworkManager{
    func loadUserInfo(completion:@escaping (_ dict:[String:AnyObject])->()){
        let urlString = "https://api.weibo.com/2/users/show.json"
        guard let uid = useAccount.uid else {
            return
        }
        let params = ["uid":uid]
        tokenRequest(URLString: urlString, parameters: params as [String : AnyObject]?) { (dict, issuccess) in
            if issuccess {
                completion(dict as! [String : AnyObject])
            }else{
                print("失败了啊点了；卡；来打卡；阿兰卡；")
            }
            
        }
    }
}

//MARK:  发布微博
extension WBNetworkManager{
    /// 发布微博
    ///
    /// - parameter text:       要发布的文本
    /// - parameter image:      要上传的图像，为 nil 时，发布纯文本微博
    /// - parameter completion: 完成回调
    func postStatus(text: String, image: UIImage?, completion: @escaping (_ result: [String: AnyObject]?, _ isSuccess: Bool)->()) -> () {
        
        // 1. url
        let urlString: String
        
        // 根据是否有图像，选择不同的接口地址
        if image == nil {
            urlString = "https://api.weibo.com/2/statuses/update.json"
        } else {
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        }
        
        // 2. 参数字典
        let params = ["status": text]
        
        // 3. 如果图像不为空，需要设置 name 和 data
        var name: String?
        var data: Data?
        
        if image != nil {
            name = "pic"
            data = UIImagePNGRepresentation(image!)
        }
        
        // 4. 发起网络请求
        tokenRequest(method: .POST, URLString: urlString, parameters: params as [String : AnyObject], name: name, data: data) { (json, isSuccess) in
            completion(json as? [String: AnyObject], isSuccess)
        }
    }
    
}


// MARK: - OAuth相关方法
extension WBNetworkManager {
    
    /// 提问：网络请求异步到底应该返回什么？-需要什么返回什么？
    /// 加载 AccessToken
    ///
    /// - parameter code:       授权码
    /// - parameter completion: 完成回调[是否成功]
    func loadAccessToken(code: String,completion: @escaping (_ issuccess:Bool)->()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": WBAppKey,
                      "client_secret": WBAppSecret,
                      "grant_type": "authorization_code",
                      "code": code,
                      "redirect_uri": WBRedirectURI]
        // 发起网络请求
        required(method: .POST, URLString: urlString, parameters: params as [String : AnyObject]?) { (json, issuccess) in
            print("Token数据是：\(json?.description ?? "NO")")
            //直接用字典设置useAccount的属性（token的转换）
            self.useAccount.yy_modelSet(withJSON: json as Any)
            //请求用户信息
            self.loadUserInfo(completion: { (dict) in
                //直接用字典设置useAccount的属性（用户信息的转换）
                self.useAccount.yy_modelSet(withJSON: dict as Any)
                //把数据保存到沙盒
                self.useAccount.saveAccount()
                print(self.useAccount)
                //在读取完用户信息再完成回调
                completion(issuccess)
            })
        }
    }
}
